/**
 * @Author yinyunqi
 * @date 2018年1月31日
 * @Content 
 */
package com.yongqi.task;

import java.util.List;

import javax.annotation.Resource;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yongqi.mapper.back.TaskMapper;
import com.yongqi.model.back.Task;

@Configuration
@EnableScheduling
@Component
public class ScheduleRefreshDatabase {
    @Autowired
    TaskMapper taskMapper;
    
    @Resource(name="jobDetail")
    private JobDetail jobDetail;
    
    @Resource(name="jobTrigger")
    private CronTrigger cronTrigger;
    
    @Resource(name="scheduler")
    private Scheduler scheduler;
    
    @Scheduled(fixedRate = 1000*60*60*24)	//	每隔一天查库，根据查询结果判断是否重新设置定时任务
    public void scheduleUpdateCronTrigger() throws SchedulerException{
	CronTrigger trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
	String currentCron = trigger.getCronExpression();	//当前Trigger使用的
	List<Task> taskList = taskMapper.emailTaskQuery();
	String searchCron = "";
	if (taskList != null) {
		searchCron = taskMapper.emailTaskQuery().get(0).getCron();		//数据库中查询出来的
	}
	System.out.println(currentCron);
	System.out.println(searchCron);
	if (currentCron.equals(searchCron)) {
	    //当前与库中相同，则不刷新任务
	}else {
	    //表达式调度构建器
	    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
	    //按新的cronExpression表达式重新构建trigger
	    trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
	    trigger = trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey()).withSchedule(scheduleBuilder).build();
	    //按新的trigger重新设置job执行
	    scheduler.rescheduleJob(cronTrigger.getKey(), trigger);
	    currentCron = searchCron;
	}
	
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}

